const geolocation = function () {
  return new Promise((resolve, reject) => {
    const geolocation = new BMap.Geolocation()
    geolocation.getCurrentPosition(function (r) {
      if (this.getStatus() === 0) {
        resolve(r)
      } else {
        reject(new Error('定位失败'))
      }
    }, {
      enableHighAccuracy: true
    })
  })
}

/**
 * 百度地图 - 自定义标记覆盖物实体类
 */
class MarkerOverlay extends BMap.Overlay {
  /**
   * 构造函数
   * @param {*} point 坐标点
   * @param {*} data 数据
   * @param {*} $map 地图dom
   * @param {*} handleClickFn 点击标记点的回调
   */
  constructor(point, data, $map, handleClickFn) {
    super()
    this.point = point
    this.data = data
    this.$map = $map
    this.handleClickFn = handleClickFn
  }

  initialize(map) {
    this.map = map

    const $div = this.$div = document.createElement('div')
    $div.className = 'marker-overlay'

    const $span = document.createElement('span')
    $span.innerText = this.data.index
    $div.appendChild($span)

    $div.onclick = () => {
      this.handleClickFn(this.data)
    }

    this.$map.getPanes().labelPane.appendChild($div)
  }

  draw() {
    const pixel = this.map.pointToOverlayPixel(this.point)
    Object.assign(this.$div.style, {
      left: `${pixel.x - 11}px`,
      top: `${pixel.y - 35}px`
    })
  }
}

const searchAutoComplate = function ($map, keyword) {
  return new Promise((resolve, reject) => {
    const localSearch = new BMap.LocalSearch($map, {
      onSearchComplete() {
        const {
          Ar
        } = localSearch.getResults()
        resolve(Ar)
      }
    })

    localSearch.search(keyword)
    localSearch.gotoPage(2)
  })
}

export {
  geolocation,
  MarkerOverlay,
  searchAutoComplate
}
